package net.lgy.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.lgy.config.WebClientConfig;
import net.lgy.service.StreamService;
import net.lgy.util.JsonData;
import net.lgy.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor  //用于简化Autowired
public class StreamServiceImpl implements StreamService {

    private final WebClient webClient;

    private final WebClientConfig webClientConfig;

    @Override
    public Flux<String> handleChatStream(String token_ai_pan, String message) {


        Map<String,Object> map = new HashMap<>();
        map.put("message",message);



        return sendRequest(webClientConfig.getChatStreamPath(), map, token_ai_pan);
    }

//    发送请求
    private Flux<String> sendRequest(String path, Map<String,Object> map, String token_ai_pan) {
        try {
            String requestBodyJson = JsonUtil.obj2Json(map);

            WebClient.RequestBodySpec requestBodySpec = webClient.post()
                    .uri(path)
                    .contentType(MediaType.APPLICATION_JSON);

            if(token_ai_pan != null){
                requestBodySpec.header("token",token_ai_pan);
            }
            return requestBodySpec.
                    bodyValue(requestBodyJson)
                    .retrieve()
                    .bodyToFlux(String.class)
                    .doOnError(error->{
                        log.error("error:{}",error);
                    })
                    .doOnComplete(()->{
                        log.info("complete请求完成");
                    });
        }catch (Exception e){
            log.error("error:{}",e);
            return Flux.just("错误请求，请重试");
        }

    }

}
